package com.sanjiayi.service.impl;

import com.sanjiayi.dto.MomentPublishDTO;
import com.sanjiayi.dto.MomentDetailDTO;
import com.sanjiayi.mapper.MomentMapper;
import com.sanjiayi.pojo.Moment;
import com.sanjiayi.pojo.MomentStats;
import com.sanjiayi.result.PageResult;
import com.sanjiayi.result.QueryPageBean;
import com.sanjiayi.service.MomentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class MomentServiceImpl implements MomentService {
    private static final Logger logger = LoggerFactory.getLogger(MomentServiceImpl.class);

    @Autowired
    private MomentMapper momentMapper;

    @Override
    public void publishMoment(Integer userId, MomentPublishDTO momentPublishDTO) {
        logger.info("开始发布动态，用户ID：{}，内容：{}", userId, momentPublishDTO);
        try {
            // 参数校验
            if (userId == null || userId <= 0) {
                logger.error("用户ID不合法：{}", userId);
                throw new IllegalArgumentException("用户ID不合法");
            }
            if (momentPublishDTO == null) {
                logger.error("发布内容为空");
                throw new IllegalArgumentException("发布内容不能为空");
            }
            if (StringUtils.isEmpty(momentPublishDTO.getContent())) {
                logger.error("动态内容为空");
                throw new IllegalArgumentException("动态内容不能为空");
            }
            if (momentPublishDTO.getContent().length() > 500) {
                logger.error("动态内容超过500字：{}", momentPublishDTO.getContent().length());
                throw new IllegalArgumentException("动态内容不能超过500字");
            }
            if (momentPublishDTO.getTopic() != null && momentPublishDTO.getTopic().length() > 50) {
                logger.error("话题超过50字：{}", momentPublishDTO.getTopic().length());
                throw new IllegalArgumentException("话题不能超过50字");
            }
            
            // 构建动态对象
            Moment moment = new Moment();
            moment.setUserId(userId);
            moment.setContent(momentPublishDTO.getContent());
            moment.setTopic(momentPublishDTO.getTopic());
            
            // 处理图片列表
            if (momentPublishDTO.getImages() != null && !momentPublishDTO.getImages().isEmpty()) {
                String images = String.join(",", momentPublishDTO.getImages());
                logger.info("处理图片列表：{}", images);
                moment.setImages(images);
            }
            
            // 处理视频
            if (!StringUtils.isEmpty(momentPublishDTO.getVideos())) {
                logger.info("处理视频：{}", momentPublishDTO.getVideos());
                moment.setVideos(momentPublishDTO.getVideos());
            }
            
            // 设置创建时间
            moment.setCreateTime(new Date());
            
            // 初始化点赞数和评论数
            moment.setLikeCount(0);
            moment.setCommentCount(0);
            
            logger.info("准备保存动态：{}", moment);
            
            // 保存动态
            int result = momentMapper.publishMoment(moment);
            logger.info("动态保存结果：{}", result);
            
            if (result <= 0) {
                logger.error("动态保存失败");
                throw new RuntimeException("动态保存失败");
            }
            
            logger.info("动态发布成功，ID：{}", moment.getMomentId());
        } catch (Exception e) {
            logger.error("发布动态失败", e);
            throw e;
        }
    }

    @Override
    public PageResult getUserMoments(Integer userId, QueryPageBean queryPageBean) {
        // 参数校验
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("用户ID不合法");
        }
        if (!checkUserExists(userId)) {
            throw new IllegalArgumentException("用户不存在");
        }
        
        // 分页参数校验和处理
        if (queryPageBean == null) {
            queryPageBean = new QueryPageBean();
            queryPageBean.setCurrentPage(1);
            queryPageBean.setPageSize(10);
        }
        if (queryPageBean.getCurrentPage() == null || queryPageBean.getCurrentPage() < 1) {
            queryPageBean.setCurrentPage(1);
        }
        if (queryPageBean.getPageSize() == null || queryPageBean.getPageSize() < 1) {
            queryPageBean.setPageSize(10);
        }
        
        // 计算分页参数
        Integer start = (queryPageBean.getCurrentPage() - 1) * queryPageBean.getPageSize();
        Integer size = queryPageBean.getPageSize();
        
        // 查询数据
        List<Moment> moments = momentMapper.findByUserId(userId, start, size);
        Integer total = momentMapper.countByUserId(userId);
        
        return new PageResult(total, moments);
    }

    @Override
    public List<Moment> getRecentMoments(Integer userId, Integer limit) {
        // 参数校验
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("用户ID不合法");
        }
        if (!checkUserExists(userId)) {
            throw new IllegalArgumentException("用户不存在");
        }
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        
        return momentMapper.findRecentByUserId(userId, limit);
    }

    @Override
    public PageResult getMomentsByTopic(String topic, QueryPageBean queryPageBean) {
        // 参数校验
        if (StringUtils.isEmpty(topic)) {
            throw new IllegalArgumentException("话题不能为空");
        }
        
        // 分页参数校验和处理
        if (queryPageBean == null) {
            queryPageBean = new QueryPageBean();
            queryPageBean.setCurrentPage(1);
            queryPageBean.setPageSize(10);
        }
        if (queryPageBean.getCurrentPage() == null || queryPageBean.getCurrentPage() < 1) {
            queryPageBean.setCurrentPage(1);
        }
        if (queryPageBean.getPageSize() == null || queryPageBean.getPageSize() < 1) {
            queryPageBean.setPageSize(10);
        }
        
        // 计算分页参数
        Integer start = (queryPageBean.getCurrentPage() - 1) * queryPageBean.getPageSize();
        Integer size = queryPageBean.getPageSize();
        
        // 查询数据
        List<Moment> moments = momentMapper.findByTopic(topic, start, size);
        Integer total = momentMapper.countByTopic(topic);
        
        return new PageResult(total, moments);
    }

    @Override
    public boolean checkUserExists(Integer userId) {
        if (userId == null || userId <= 0) {
            return false;
        }
        return momentMapper.checkUserExists(userId) > 0;
    }

    @Override
    public MomentStats getUserMomentStats(Integer userId) {
        // 参数校验
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("用户ID不合法");
        }
        if (!checkUserExists(userId)) {
            throw new IllegalArgumentException("用户不存在");
        }
        
        return momentMapper.getUserMomentStats(userId);
    }

    @Override
    public PageResult getRecommendMoments(QueryPageBean queryPageBean, String type) {
        try {
            logger.info("开始获取推荐动态，类型：{}，页码：{}，每页大小：{}", 
                type, queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
            
            // 分页参数校验和处理
            if (queryPageBean == null) {
                queryPageBean = new QueryPageBean();
                queryPageBean.setCurrentPage(1);
                queryPageBean.setPageSize(10);
            }
            if (queryPageBean.getCurrentPage() == null || queryPageBean.getCurrentPage() < 1) {
                queryPageBean.setCurrentPage(1);
            }
            if (queryPageBean.getPageSize() == null || queryPageBean.getPageSize() < 1) {
                queryPageBean.setPageSize(10);
            }
            
            // 计算分页参数
            Integer start = (queryPageBean.getCurrentPage() - 1) * queryPageBean.getPageSize();
            Integer size = queryPageBean.getPageSize();
            
            logger.info("计算后的分页参数：start={}, size={}", start, size);
            
            List<Moment> moments;
            Integer total;
            
            // 根据类型查询不同的推荐内容
            if ("hot".equals(type)) {
                logger.info("查询热门动态");
                moments = momentMapper.findHotMoments(start, size);
                total = momentMapper.countAllMoments();
            } else {
                logger.info("查询最新动态");
                moments = momentMapper.findAllMoments(start, size);
                total = momentMapper.countAllMoments();
            }
            
            logger.info("查询结果：total={}, moments.size={}", total, moments != null ? moments.size() : 0);
            
            return new PageResult(total, moments);
        } catch (Exception e) {
            logger.error("获取推荐动态失败", e);
            throw e;
        }
    }

    @Override
    public Moment getMomentById(String id) {
        try {
            return momentMapper.selectById(Integer.parseInt(id));
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public MomentDetailDTO getMomentDetail(Integer momentId, Integer userId) {
        return momentMapper.getMomentDetail(momentId, userId);
    }

    @Override
    public PageResult getFollowingMoments(Integer userId, QueryPageBean queryPageBean) {
        logger.info("开始获取关注用户的动态，用户ID：{}，页码：{}，每页大小：{}", 
            userId, queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
            
        // 参数校验
        if (userId == null || userId <= 0) {
            logger.error("用户ID不合法：{}", userId);
            throw new IllegalArgumentException("用户ID不合法");
        }
        
        // 分页参数校验和处理
        if (queryPageBean == null) {
            queryPageBean = new QueryPageBean();
            queryPageBean.setCurrentPage(1);
            queryPageBean.setPageSize(10);
        }
        if (queryPageBean.getCurrentPage() == null || queryPageBean.getCurrentPage() < 1) {
            queryPageBean.setCurrentPage(1);
        }
        if (queryPageBean.getPageSize() == null || queryPageBean.getPageSize() < 1) {
            queryPageBean.setPageSize(10);
        }
        
        try {
            // 计算分页参数
            Integer start = (queryPageBean.getCurrentPage() - 1) * queryPageBean.getPageSize();
            Integer size = queryPageBean.getPageSize();
            
            logger.info("计算后的分页参数：start={}, size={}", start, size);
            
            // 查询数据
            List<Moment> moments = momentMapper.findFollowingMoments(userId, start, size);
            Integer total = momentMapper.countFollowingMoments(userId);
            
            logger.info("查询结果：total={}, moments.size={}", total, moments != null ? moments.size() : 0);
            
            return new PageResult(total, moments);
        } catch (Exception e) {
            logger.error("获取关注用户动态失败", e);
            throw new RuntimeException("获取关注用户动态失败", e);
        }
    }
} 